<template>
  <rx-dialog @handOk="savePmt" @cancel="cancel">
      <div style="padding: 10px;height:100%">
            <a-form-model :form="form" >
                <a-row >
                    <a-col :span="12">
                <a-form-model-item :label="$ti18('rxForm.name','名称')" :labelCol="labelCol" :wrapper-col="wrapperCol">
                    <a-input  v-model="name"/>
                </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item :label="i18n('list.dataList','单据列表')"   :labelCol="labelCol" :wrapper-col="wrapperCol">
                            <a-input disabled="" style="width:calc(100% - 83px)" v-model="boListName"/>
                            <a-button type="primary" icon="select" v-if="type == 'add'"   @click="selectBo">{{$ti18('rxList.select','选择')}}</a-button>
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item :label="i18n('form.userGroup','用户组')"   :labelCol="labelCo" :wrapper-col="wrapperCo">
                            <rx-textboxlist  ref="valueList" v-model="values">
                                <a-icon  type="setting" @click="selectGroups" />
                            </rx-textboxlist>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form-model>
            <a-tabs style="height: calc(100% - 120px);" defaultActiveKey="buttonField" :tabBarStyle="{borderBottom:0}" @tabClick="onTabClick">
                <a-tab-pane forceRender :tab="i18n('form.buttonPower','按钮权限')" key="buttonField">
                    <rx-grid ref="table_button" :selectRowKeys="selectRowButtonKeys" :dataSource="grantButtons"
                             :columns="grantButtonColumns" :allowRowSelect="true" :multiSelect="true" :showPage="false"
                             :bordered="true" id-field="btnName">
                    </rx-grid>
                </a-tab-pane>

                <a-tab-pane forceRender :tab="i18n('form.dataPermission','数据权限')" key="dataList">
                    <rx-grid ref="table_list"
                             :selectRowKeys="selectRowListKeys"
                             :dataSource="grantLists"
                             :columns="grantColumns"
                             :allowRowSelect="true"
                             :multiSelect="true"
                             :showPage="false"
                             :bordered="true"
                    >
              <span slot="op" slot-scope="{text,record,index,blur}">
          <a-select style="width:100%;" labelInValue v-model="record.op" @blur="blur(index,'op',text,record)">
            <a-select-option value="=">{{i18n('options.equal','等于')}}</a-select-option>
            <a-select-option value="in">{{i18n('options.range','范围')}}</a-select-option>
          </a-select>
        </span>
                        <span slot="scope" slot-scope="{text,record,index,blur}">
          <a-select style="width:100%;" v-if="record.type=='user' && record.op=='='" labelInValue v-model="record.scope"
                    @blur="blur(index,'scope',text,record)">
                  <a-select-option value="SELF">{{i18n('options.oneself','自己')}}</a-select-option>
                  <a-select-option value="DUP_USERS">{{i18n('options.dupUsers','直属上级用户')}}</a-select-option>
                  <a-select-option value="UP_USERS">{{i18n('options.upUsers','所有上级用户')}}</a-select-option>
                  <a-select-option value="DDOWN_USERS">{{i18n('options.ddownUsers','直属下级用户')}}</a-select-option>
                  <a-select-option value="DOWN_USERS">{{i18n('options.downUsers','所有下级用户')}}</a-select-option>
              <a-select-option value="CHARGE_DEPT_USERS">{{i18n('options.chargeDeptUsers','负责人的组内用户')}}</a-select-option>
          </a-select>
          <a-select style="width:100%;" v-if="record.type=='group' && record.op=='='" labelInValue
                    v-model="record.scope" @blur="blur(index,'scope',text,record)">
                  <a-select-option value="SELF_DEP">{{i18n('options.selfDep','默认部门')}}</a-select-option>
                  <a-select-option value="DUP_DEPS">{{i18n('options.dupDeps','直属上级部门')}}</a-select-option>
                  <a-select-option value="UP_DEPS">{{i18n('options.upDeps','所有上级部门')}}</a-select-option>
                  <a-select-option value="DDOWN_DEPS">{{i18n('options.ddownDeps','本部门及下级部门')}}</a-select-option>
                  <a-select-option value="DOWN_DEPS">{{i18n('options.downDeps','所有下级部门')}}</a-select-option>
          </a-select>
          <a-select style="width:100%;" v-if="record.type=='inst' && record.op=='='" labelInValue v-model="record.scope"
                    @blur="blur(index,'scope',text,record)">
                  <a-select-option value="SELF_TENANT">{{i18n('options.selfTenant','作者机构')}}</a-select-option>
                  <a-select-option value="DUP_TENANTS">{{i18n('options.dupTenants','上级机构')}}</a-select-option>
                  <a-select-option value="UP_TENANTS">{{i18n('options.upTenants','所有上级机构')}}</a-select-option>
                  <a-select-option value="DDOWN_TENANTS">{{i18n('options.ddownTenants','直属下级机构')}}</a-select-option>
                  <a-select-option value="DOWN_TENANTS">{{i18n('options.downTenants','所有下级机构')}}</a-select-option>
          </a-select>
          <a-input style="width:100%;" v-model="record.scope" @blur="blur(index,'scope',text,record)"
                   v-if="record.type=='field' && record.op=='=' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"/>
          <a-input-number style="width:100%;" v-model="record.scope" @blur="blur(index,'scope',text,record)"
                          v-if="record.type=='field' && record.dataType=='number'"/>
          <a-date-picker style="width:100%;" showTime format="YYYY-MM-DD"
                         @change="gridChangeDate($event,$event,{record:record,dataIndex:'scope',format:'YYYY-MM-DD'})"
                         @ok="blur(index,'scope',text,record)" v-if="record.type=='field' && record.dataType=='date'"/>
          <rx-input-button style="width:100%;"
                           @click="selUserData($event,{field:'scope',text:text,record:record,index:index,blur:blur})"
                           v-if="record.type=='user' && record.op=='in'"/>
          <rx-input-button style="width:100%;"
                           @click="selGroupData($event,{field:'scope',text:text,record:record,index:index,blur:blur})"
                           v-if="record.type=='group' && record.op=='in'"/>
          <rx-input-button style="width:100%;"
                           @click="selTenantData($event,{field:'scope',text:text,record:record,index:index,blur:blur})"
                           v-if="record.type=='inst' && record.op=='in'"/>
          <rx-input-button style="width:100%;"
                           @click="rangSetDlg($event,{field:'scope',text:text,record:record,index:index,blur:blur})"
                           v-if="record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"/>
        </span>
                        <span slot="scope2" slot-scope="{text,record,index,blur}">
          <a-input-number style="width:100%;" v-model="record.scope2" @blur="blur(index,'scope2',text,record)"
                          v-if="record.type=='field' && record.op=='in' && record.dataType=='number'"/>
          <a-date-picker style="width:100%;" showTime format="YYYY-MM-DD"
                         @change="gridChangeDate($event,$event,{record:record,dataIndex:'scope2',format:'YYYY-MM-DD'})"
                         @ok="blur(index,'scope2',text,record)"
                         v-if="record.type=='field' && record.op=='in' && record.dataType=='date'"/>
          <a-select style="width:100%;" mode="tags" labelInValue :options="getSelectData(record)"
                    @change="gridChangeSelect($event,record,'scope2')" @blur="blur(index,'scope2',text,record)"
                    v-if="record.scope=='selfData' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"/>
          <rx-select style="width:100%;" :multiSelect="true" :labelInValue="true"
                     @change="gridChangeSelect($event,record,'scope2')" @blur="blur(index,'scope2',text,record)"
                     ajaxType="post" :url="'/api-form/form/core/formCustomQuery/queryForJson_'+record.configs.sql" data-field="data"
                     :valueField="record.configs.valueField" :textField="record.configs.textField"
                     v-if="record.scope=='sql' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"/>
          <rx-select style="width:100%;" :multiSelect="true" :labelInValue="true"
                     @change="gridChangeSelect($event,record,'scope2')" @blur="blur(index,'scope2',text,record)"
                     :url="'/api-system/system/core/sysDic/getByAlias?alias='+record.configs.dic+'&i18nTransform=true'" value-field="value"
                     text-field="name"
                     v-if="record.scope=='dic' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"/>
          <rx-input-button style="width:100%;"
                           @click="showDialog($event,{field:'scope2',text:text,record:record,index:index,blur:blur})"
                           v-if="record.scope=='dialog' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"/>
        </span>
                    </rx-grid>
                </a-tab-pane>
                <a-tab-pane forceRender :tab="i18n('form.fieldPermiss','字段权限')" key="dataField">
                    <rx-grid ref="table_field"
                             :selectRowKeys="selectRowFieldKeys"
                             :dataSource="grantFields"
                             :columns="grantFieldColumns"
                             :allowRowSelect="true"
                             :multiSelect="true"
                             :showPage="false"
                             :bordered="true"
                             id-field="field"
                    >
                    </rx-grid>
                </a-tab-pane>

                <a-tab-pane forceRender :tab="i18n('form.previewSql','预览SQL')" key="previewSql">
                   <div class="SQL"> {{sql}}</div>
                </a-tab-pane>
            </a-tabs>
      </div>
  </rx-dialog>
</template>
<script>
  import FormBoPmtApi from '@/api/form/core/formBoPmt';
  import FormBoListApi from "@/api/form/core/formBoList";
  import FormBoPmtDialog from "./FormBoPmtDialog";
  import {BaseForm, Dialog, Util} from "@lowcode/jpaas-common-lib";


  export default {
    name: 'FormBoPmtEdit',
    mixins: [BaseForm],
    components: {
        Dialog
    },
    props: {
        type: {
        type: String,
        default: ""
      },
        listId: '',
        listName: '',
        listKey: ''
    },
    data() {
      return {
          sql: '',
          name: '',
          pmtId: '',
          boListId: '',
          boListName: '',
          boListKey: '',
          group: {
              values:"",
              names:""
          },
          values: {
              value:"",
              text:""
          },
          valueList: {
              values: [],
              names: []
          },
          selectRowButtonKeys: [],
          selectRowListKeys:[],
          selectRowFieldKeys:[],
          grantButtons: [],
          grantLists:[],
          grantFields:[],
          grantButtonColumns: [{
              title: this.i18n('form.buttonName','按钮名称'),
              dataIndex: 'btnLabel',
              width: 180
          }, {
              title: this.i18n('form.buttonMark','按钮标识'),
              dataIndex: 'btnName',
              width: 180
          }],
          grantFieldColumns:[{title: this.i18n('form.fieldName','字段名称'), dataIndex: 'header',width:180}, {title: '字段Key', dataIndex: 'field',width:180}],
          grantColumns:[{title: this.i18n('form.permissionType','权限类型'), dataIndex: 'type',displayField: 'type_name',scopedSlots: {customRender: 'type'}},
              {
                  title: this.i18n('form.permissionDesc','权限描述'),
                  dataIndex: 'desc',
                  displayField: 'desc',
                  scopedSlots: {customRender: 'desc'}
              },
              {
                  title: this.i18n('form.filterField','筛选字段'),
                  dataIndex: 'field',
                  displayField: 'field_name',
                  scopedSlots: {customRender: 'field'}
              },
              {
                  title: this.i18n('form.comparator','比较符'),
                  dataIndex: 'op',
                  displayField: 'op_name',
                  allowCellEdit: true,
                  scopedSlots: {customRender: 'op'}
              },
              {
                  title: this.i18n('form.scope1','作用域1'),
                  dataIndex: 'scope',
                  displayField: 'scope_name',
                  allowCellEdit: true,
                  scopedSlots: {customRender: 'scope'}
              },
              {
                  title: this.i18n('form.scope2','作用域2'),
                  dataIndex: 'scope2',
                  displayField: 'scope2_name',
                  allowCellEdit: true,
                  scopedSlots: {customRender: 'scope2'}
              }],
              labelCo: { span: 3 },
               wrapperCo: { span: 15 },

      }
    },
    created(){
        this.initGrant();
      },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"FormBoPmt",key);
        },
        initGrant(){
            if(this.type == 'grant'){
                this.boListId = this.listId;
                this.boListName = this.listName;
                this.boListKey = this.listKey;
                this.getPmt("", this.boListKey);
            }
        },
      get(id) {
        var serf_ = this;
        return FormBoPmtApi.get(id).then(res => {
            var data = res.data;
            serf_.name = data.name;
            serf_.boListName = data.boListName;
            serf_.boListId = data.boListId;
            serf_.pmtId = data.pmtId;
            serf_.getPmt(data.pmtId);
        })
      },
        getPmt(pmtId, boListKey){
            var self=this;
            if(!pmtId){
                self.grantButtons=[];
                self.grantLists=[];
                self.grantFields=[];
                self.selectRowButtonKeys=[];
                self.selectRowListKeys=[];
                self.selectRowFieldKeys=[];

            }
            FormBoListApi.getGrantJsonByKey(pmtId, boListKey).then(res=>{
                self.grantButtons=res['BUTTON'];
                self.grantLists=res['LIST'];
                self.grantFields=res['FIELD'];
                if(res['BUTTON_Keys']) {
                    self.selectRowButtonKeys = res['BUTTON_Keys'];
                }
                if(res['LIST_Keys']) {
                    self.selectRowListKeys = res['LIST_Keys'];
                }
                if(res['FIELD_Keys']) {
                    self.selectRowFieldKeys = res['FIELD_Keys'];
                }

                if(res['groupIds']){
                    var values = res['groupIds'].split(",");
                    var names = res['groupNames'].split(",");
                    for (var i = 0; i < values.length; i++) {
                        this.valueList.values.push(values[i]);
                        this.valueList.names.push(names[i]);
                    }
                    this.sendChangeValue();
                }


            })
        },
        selectBo() {
            let _self =this;
            Util.open({
                component: FormBoPmtDialog,
                curVm:this,
                widthHeight: ['800px', '700px'],
                data:{
                    setting:{}
                },
                title: _self.i18n('list.formList','单据列表')
            },function (action,data){
                if(action!='ok'){
                    return;
                }
                if(data){
                    _self.boListId = data.id;
                    _self.boListName = data.name;
                    if(data.id){
                        _self.getPmt("", data.key);
                    }

                };

            });
        },
        selectGroups() {
            var conf = {curVm: this, data: {single: false,showDimId:true}, widthHeight: ['900px', '700px']};
            Dialog.openGroupDialog(conf, function (self, data) {
                for (var i = 0; i < data.length; i++) {
                    var obj = data[i];
                    if (self.valueList.values.indexOf(obj.groupId) == -1) {
                        self.valueList.values.push(obj.groupId);
                        self.valueList.names.push(obj.name);
                    }
                }
                self.sendChangeValue();
            })
        },
        sendChangeValue() {
            var changeValues = {
                value: this.valueList.values.join(","),
                text: this.valueList.names.join(",")
            };
            this.$refs.valueList.setValues(changeValues, false);
        },
        onTabClick(targetKey) {
            if(targetKey  == 'previewSql'){
                if(!this.boListId){
                    this.sql = this.i18n('msa.selFormListTips','请选择单据列表！');
                    return ;
                }
                var json={};
                json['LIST']={type:'LIST',boListId:this.boListId,
                    datas:this.$refs.table_list.getSelectedRows()};
                FormBoPmtApi.previewSql(JSON.stringify(json)).then(res=>{
                    if(res.success){
                        this.sql = res.data;
                    }else{
                        this.sql = this.i18n('msa.notDataYet','暂无数据');

                    }
                })
            }
        },
        savePmt(vm){
            if(!this.name){
                this.$message.error(this.i18n('msa.nameNotEmpty','名称不能为空!'));
                vm.loading = false;
                return;
            }
            if(!this.group.values){
                this.$message.error(this.i18n('msa.selUserGroupTips','请选择用户组!'));
                vm.loading = false;
                return;
            }
            if(!this.boListId){
                this.$message.error(this.i18n('msa.selFormListTips','请选择单据列表！'));
                vm.loading = false;
                return;
            }
            var json={};
            json['LIST']={type:'LIST',pmtId:this.pmtId,name:this.name,groupIds:this.group.values,boListId:this.boListId,
                buttons:this.$refs.table_button.getSelectedRows(),datas:this.$refs.table_list.getSelectedRows(),fields:this.$refs.table_field.getSelectedRows()};
            let _self =  this  ;
            FormBoPmtApi.saveGrantJson(JSON.stringify(json)).then(res=>{
                if(res.success){
                    Util.closeWindow(_self,"ok",this.map);
                }else{
                    this.$message.error(res.message);
                    vm.loading = false;

                }
            })
        }

    },
      watch: {
          values: function (val) {
              this.group.values = val.value;
              this.group.names = val.text;
              if(val.value){
                  this.valueList.values=val.value.split(",");
                  this.valueList.names=val.text.split(",");
              }else {
                  this.valueList.values=[];
                  this.valueList.names=[];
              }

          }
      }
  }
</script>
<style scoped>
    .SQL{
        border:1px solid #ddd;
        height:200px;
        padding: 10px;
        margin-top: 10px;
        border-radius: 10px;
    }
  .tableTit {
    margin: 10px 10px 10px 0px;
    border-left: 2px solid #1890ff;
    padding-left: 6px;
    height: 14px;
    line-height: 14px;
  }

  * >>> .ant-table-row td:last-child .MyfixedBoxs {
    right: 10px;
  }
</style>